package com.jch.dm.chapter_23_interpreter;

import java.util.StringTokenizer;

/**
 * @author: Administrator
 * @create: 2020/04/14 17:57
 **/
public class Context {

    private StringTokenizer tokenizer;

    private String currentToken;

    public Context(String text) {
        tokenizer = new StringTokenizer(text);
        nextToken();
    }

    /**
     * 下一个token
     * @return
     */
    public String nextToken() {
        if (tokenizer.hasMoreTokens()){
            currentToken = tokenizer.nextToken();
        }else{
            currentToken = null;
        }
        return currentToken;
    }

    /**
     * 创建token
     * @return
     */
    public String currentToken(){
        return currentToken;
    }

    public void skipToken(String token)throws ParseException{
        if (!token.equals(currentToken)){
            throw new ParseException("Warning:"+token+" is expected,but "+currentToken+" is found.");
        }
        nextToken();
    }

    public int currentNumber()throws ParseException{
        int number = 0;
        try {
            number = Integer.parseInt(currentToken);
        }catch (NumberFormatException e){
            throw new ParseException("Warning:" + e);
        }
        return number;
    }
}
